﻿using System.Linq.Expressions;
using AutoMapper;
using CarAppDomain.CarType.IRepository;
using CarAppDomain.CarType.IService;
using CarAppDomain.CarType.Entities;
using CarAppDto.CarType.CarDtos;
using D.Util.UtilCache;
using D.UtilCore.Dtos;
using D.UtilCore.Utils;
using D.UtilSqlsugarOrm;
using CarAppDto.CarType.CarTypeDtos;
using CarAppDomain.CarParts.Entities;
using CarAppDomain.CarParts.IRepository;
using CarAppDto.CarType.AreaDtos;
using CarAppDto.CarType.CountryDtos;
using CarAppDto.Dtos;
using CarAppDto.CarParts.CarPartsDtos;
using CarAppDto.CarType.CarTypeVersionDtos;

namespace CarAppDomain.CarType.Service
{
    public class CarTypeService : BaseService<CarTypeEntity>, ICarTypeService
    {
        private readonly IMapper _mapper;
        private readonly ICacheService _cache;
        private readonly ICarTypeEntityRepository _repository;
        private readonly ICarPartsEntityRepository _repositoryCarParts;
        private readonly IAreaEntityRepository _repositoryArea;
        private readonly ICountryEntityRepository _repositoryCountry;
        private readonly IBrandEntityRepository _repositorBrand;
        /// <summary>
        /// 构造注入
        /// </summary>
        public CarTypeService(IMapper mapper, ICacheService cache, ICarTypeEntityRepository repository, ICarPartsEntityRepository repositoryCarParts
            , IAreaEntityRepository repositoryArea, ICountryEntityRepository repositoryCountry, IBrandEntityRepository repositorBrand)
        {
            // 用于base方法
            base._baseDal = repository;
            this._repository = repository;
            _repositoryCarParts = repositoryCarParts;
            _repositoryArea = repositoryArea;
            _repositoryCountry = repositoryCountry;
            _repositorBrand = repositorBrand;
            _cache = cache;
            _mapper = mapper;
        }

        #region 增删改查


        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> AddCarTypeAsync(ReqAddCarType reqModel)
        {
            var exists = await _repository.ExistsAsync(m => m.Name == reqModel.Name||m.Code==reqModel.Code);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "名称或编号重复" };
            }
            if (!string.IsNullOrWhiteSpace(reqModel.SaleAreaId))
            {
                exists = await _repositoryArea.ExistsAsync(m => m.Id == reqModel.SaleAreaId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "销售区域不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.ManufacturingCountryId))
            {
                exists = await _repositoryCountry.ExistsAsync(m => m.Id == reqModel.ManufacturingCountryId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "制造国家不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
            {
                exists = await _repositorBrand.ExistsAsync(m => m.Id == reqModel.BrandId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "品牌信息不存在" };
                }
            }
            var insertEntity = _mapper.Map<ReqAddCarType, CarTypeEntity>(reqModel);
            insertEntity.DeleteFlag = false;
            insertEntity.CreateTime = DateTime.Now;
            insertEntity.Id = Guid.NewGuid().ToString();
            List<CarPartsCarTypeEntity> carPartsVehicleSeriesList = new List<CarPartsCarTypeEntity>();
            foreach (CarPartsCarType item in reqModel.CarParts)
            {
                var carParts = await _repositoryCarParts.GetModelAsync(m => m.Id == item.CarPartsId);
                if (carParts == null)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "配件ID不存在" };
                }
                else
                {
                    CarPartsCarTypeEntity carPartsVehicleSeries = new CarPartsCarTypeEntity();
                    carPartsVehicleSeries.CarPartsId = item.CarPartsId;
                    carPartsVehicleSeries.SerialNumber = item.SerialNumber;
                    carPartsVehicleSeries.State = item.State;
                    carPartsVehicleSeries.ReplacedCarPartsId = item.ReplacedCarPartsId;
                    carPartsVehicleSeries.CreateTime = DateTime.Now;
                    carPartsVehicleSeries.CreateUser = insertEntity.CreateUser;
                    carPartsVehicleSeriesList.Add(carPartsVehicleSeries);
                }
            }
            var dbres = await _repository.AddCarTypeAsync(insertEntity, carPartsVehicleSeriesList);

            return dbres.NormalResponse();
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> DeleteCarTypeAsync(List<string> ids)
        {
            var dbres = await _repository.DeleteCarTypeAsync(ids);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<int>> UpdateCarTypeAsync(ReqUpdateCarType reqModel)
        {
            var updateEntity = await _repository.GetModelAsync(m => m.Id == reqModel.Id);
            if (updateEntity == null)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "该信息不存在" };
            }
            var exists = await _repository.ExistsAsync(m => (m.Name == reqModel.Name || m.Code == reqModel.Code) && m.Id != reqModel.Id);
            if (exists)
            {
                return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "名称或编号重复" };
            }
            if (!string.IsNullOrWhiteSpace(reqModel.SaleAreaId))
            {
                exists = await _repositoryArea.ExistsAsync(m => m.Id == reqModel.SaleAreaId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "销售区域不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.ManufacturingCountryId))
            {
                exists = await _repositoryCountry.ExistsAsync(m => m.Id == reqModel.ManufacturingCountryId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "制造国家不存在" };
                }
            }
            if (!string.IsNullOrWhiteSpace(reqModel.BrandId))
            {
                exists = await _repositorBrand.ExistsAsync(m => m.Id == reqModel.BrandId);
                if (!exists)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "品牌信息不存在" };
                }
            }
            updateEntity.BrandId = reqModel.BrandId;
            updateEntity.VehicleSeriesId = reqModel.VehicleSeriesId;
            updateEntity.Name = reqModel.Name;
            updateEntity.EnglishName= reqModel.EnglishName;
            updateEntity.Code = reqModel.Code;
            updateEntity.VehicleSeriesId= reqModel.VehicleSeriesId;
            updateEntity.SaleAreaId= reqModel.SaleAreaId;
            updateEntity.ManufacturingCountryId= reqModel.ManufacturingCountryId;
            updateEntity.ModelYearCode= reqModel.ModelYearCode;
            updateEntity.CatalogNo = reqModel.CatalogNo;
            updateEntity.MarketingTime = reqModel.MarketingTime;
            updateEntity.DownTime = reqModel.DownTime;
            updateEntity.Image= reqModel.Image;
            updateEntity.UpdateTime = DateTime.Now;
            updateEntity.UpdateUser = reqModel.UpdateUser;
            updateEntity.VehicleModel = reqModel.VehicleModel;
            updateEntity.VehicleType = reqModel.VehicleType;
            
            List<CarPartsCarTypeEntity> carPartsVehicleSeriesList = new List<CarPartsCarTypeEntity>();
            foreach (CarPartsCarType item in reqModel.CarParts)
            {
                var carParts = await _repositoryCarParts.GetModelAsync(m => m.Id == item.CarPartsId);
                if (carParts == null)
                {
                    return new ApiResult<int>() { Code = StatusCodeEnum.Waring, ErrorMsg = "配件ID不存在" };
                }
                else
                {
                    CarPartsCarTypeEntity carPartsVehicleSeries = new CarPartsCarTypeEntity();
                    carPartsVehicleSeries.CarPartsId = item.CarPartsId;
                    carPartsVehicleSeries.SerialNumber = item.SerialNumber;
                    carPartsVehicleSeries.State = item.State;
                    carPartsVehicleSeries.CarTypeId = reqModel.Id;
                    carPartsVehicleSeries.ReplacedCarPartsId = item.ReplacedCarPartsId;
                    carPartsVehicleSeries.CreateTime = DateTime.Now;
                    carPartsVehicleSeries.CreateUser = reqModel.UpdateUser;
                    carPartsVehicleSeriesList.Add(carPartsVehicleSeries);
                   
                }
            }
            var dbres = await _repository.UpdateCarTypeAsync(updateEntity, carPartsVehicleSeriesList);
            return dbres.NormalResponse();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="reqModel"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepCarType>>> QueryCarTypeListAsync(ReqQueryCarTypeList reqQueryPage)
        {
            Expression<Func<CarTypeEntity, bool>> where = null;
            if (!string.IsNullOrEmpty(reqQueryPage.Name))
            {
                where = where.And(m => m.Name.Contains(reqQueryPage.Name));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.EnglishName))
            {
                where = where.And(m => m.EnglishName.Contains(reqQueryPage.EnglishName));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.SaleAreaId))
            {
                where = where.And(m => m.SaleAreaId == reqQueryPage.SaleAreaId);
            }
            if (!string.IsNullOrEmpty(reqQueryPage.ManufacturingCountryId))
            {
                where = where.And(m => m.ManufacturingCountryId == reqQueryPage.ManufacturingCountryId);
            }
            if (!string.IsNullOrEmpty(reqQueryPage.VehicleSeriesId))
            {
                where = where.And(m => m.VehicleSeriesId == reqQueryPage.VehicleSeriesId);
            }
            if (reqQueryPage.IsDown != null)
            {
                if (reqQueryPage.IsDown == true)
                    where = where.And(m => m.DownTime != null);
                else
                    where = where.And(m => m.DownTime == null);
            }
        
            var dbres = await _repository.GetListAsync(where);
            var res = _mapper.Map<List<CarTypeEntity>, List<RepCarType>>(dbres);        
            return res.GetResponse();
        }

        /// <summary>
        /// 查询单个
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<RepCarType>> GetCarTypeAsync(string id)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == id);
            var res = _mapper.Map<CarTypeEntity, RepCarType>(dbres);
            var resCarType = await _repositoryCarParts.GetCarPartsCarType(res.Id);
            res.CarPartsList = resCarType;
            return res.GetResponse();
        }

        public async Task<ApiResult<PageModel<RepCarType>>> QueryCarTypePagesAsync(ReqQueryCarTypePage reqQueryPage)
        {
            Expression<Func<CarTypeEntity, bool>> where = null;
            if (!string.IsNullOrEmpty(reqQueryPage.Name))
            {
                where = where.And(m => m.Name.Contains(reqQueryPage.Name));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.EnglishName))
            {
                where = where.And(m => m.EnglishName.Contains(reqQueryPage.EnglishName));
            }
            if (!string.IsNullOrEmpty(reqQueryPage.SaleAreaId))
            {
                where = where.And(m => m.SaleAreaId == reqQueryPage.SaleAreaId);
            }
            if (!string.IsNullOrEmpty(reqQueryPage.ManufacturingCountryId))
            {
                where = where.And(m => m.ManufacturingCountryId == reqQueryPage.ManufacturingCountryId);
            }
            if (!string.IsNullOrEmpty(reqQueryPage.VehicleSeriesId))
            {
                where = where.And(m => m.VehicleSeriesId == reqQueryPage.VehicleSeriesId);
            }
            if (reqQueryPage.IsDown != null)
            {
                if (reqQueryPage.IsDown == true)
                    where = where.And(m => m.DownTime != null);
                else
                    where = where.And(m => m.DownTime == null);
            }

            Expression<Func<CarTypeEntity, object>> order = null;
            bool orderByAsc = true;
            if (reqQueryPage.Sorts != null && reqQueryPage.Sorts?.Count != 0)
            {
                SortDto sortDtoFrist = reqQueryPage.Sorts.FirstOrDefault();
                string sortField = sortDtoFrist?.Field;
                string sortOrder = sortDtoFrist?.Sort;
                order = ExpressionUtil.GetOrderObjectExpression<CarTypeEntity>(sortField, sortOrder, ref orderByAsc);
            }
            else
                order = m => m.CreateTime;

            var dbres = await _repository.GetOrderPagesAsync(reqQueryPage.PageSize, reqQueryPage.PageNo, where, order, orderByAsc);
            var dbresData = _mapper.Map<List<CarTypeEntity>, List<RepCarType>>(dbres.Data);
            //foreach (RepCarType item in dbresData)
            //{
            //    var resCarType = await _repositoryCarParts.GetCarPartsListByCarType(item.Id);
            //    item.CarPartsList = resCarType;
            //}
            var res = new PageModel<RepCarType>()
            {
                PageNo = dbres.PageNo,
                PageSize = dbres.PageSize,
                TotalCount = dbres.TotalCount,
                TotalPage = dbres.TotalPage,
                Data = dbresData
            };
            return res.GetResponse();
        }

        /// <summary>
        /// 获取车型的全部配件
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ApiResult<List<RepCarParts>>> GetCarPartsByCarTypeIdAsync(string carTypeId)
        {
            var dbres = await _repository.GetModelAsync(m => m.Id == carTypeId);
            var res = _mapper.Map<CarTypeEntity, RepCarType>(dbres);
            var resCarType = await _repositoryCarParts.GetCarPartsByCarTypeId(res.VehicleSeriesId,res.Id);
            return resCarType.GetResponse(); 
        }

        #endregion
    }
}
